from django.shortcuts import render, redirect
from django import forms
from www import models
from utils.bootstrap import BootStrapForm
from utils.encrypt import md5_string
from django.contrib import messages


class ResetPasswordForm(BootStrapForm, forms.ModelForm):
    confirm_password = forms.CharField(label="重复密码", widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Customer
        fields = ['password', 'confirm_password']
        widgets = {'password': forms.PasswordInput}


class InfoModelForm(BootStrapForm, forms.ModelForm):
    repeat_password = forms.CharField(label='重复密码', widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Customer
        fields = ['password', 'repeat_password']

    def clean_password(self):
        return md5_string(self.cleaned_data['password'])

    def clean_repeat_password(self):
        repeat_password = md5_string(self.cleaned_data['repeat_password'])
        if repeat_password != self.cleaned_data['password']:
            raise forms.ValidationError("密码不一致")
        return repeat_password


def info_list(request):
    instance = models.Customer.objects.filter(id=request.nb_user.id, active=1).first()
    # 获取当前用户信息，生成表单
    if request.method == 'GET':
        form = InfoModelForm()
        context = {
            "instance": instance,
            "form": form,
        }
        return render(request, 'user/info_list.html', context)
    form = InfoModelForm(instance=instance, data=request.POST)
    if not form.is_valid():
        context = {"instance": instance, 'form': form}
        return render(request, 'user/info_list.html', context)

    form.save()
    messages.add_message(request, messages.SUCCESS, "重置密码成功")
    return redirect('/info/list/')
